package com.sso.server.service.impl;
import com.sso.core.store.SsoLoginStore;
import com.sso.core.util.StringUtils;
import com.sso.server.service.SmsService;
import com.sso.server.util.AliSmsUtil;
import com.sso.server.util.IdUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {


    @Value("${sso.sms.ali.accessKeyId}")
    String accessKeyId;
    @Value("${sso.sms.ali.accessKeySecret}")
    String accessKeySecret;
    @Value("${sso.sms.ali.signName}")
    String signName;
    @Value("${sso.sms.ali.templateCode}")
    String templateCode;
    @Value("${sso.sms.ali.templateParamKey}")
    String templateParamName;
    @Value("${sso.sms.ali.expire.minute}")
    Integer expireMinute;

    private static final Logger logger = LogManager.getLogger(SmsServiceImpl.class);


    @Override
    public String sendMsg(String mobile) {

        String hasCode=SsoLoginStore.getSmsCode(mobile);
        if(StringUtils.isNotNull(hasCode)){
            logger.info("send sms (form cache) > {}  code={} ",mobile,hasCode);
            return "ok";
        }

        String msgCode= IdUtil.gen6Num();
        String templateParam="{\""+templateParamName+"\":\""+msgCode+"\"}";
        String r="";
        try {
           r= AliSmsUtil.send(accessKeyId,accessKeySecret,signName,templateCode,mobile,templateParam);
            SsoLoginStore.putSmsCode(mobile,msgCode,expireMinute);
           return r;
        } catch (Exception e) {
            logger.error("sendMsg error!",e);
            r=e.getMessage();
            return e.getMessage();
        }finally {
            logger.info("send sms > {}  code={}  status={}",mobile,msgCode,r);

        }


    }
}
